#include <string>
#pragma warning (disable:4996)
#include <WinSock2.h>
#include <cstring>
#include <iostream>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
uint16_t serverport = 8080;
string serverip = "8.155.55.150";
#include "udpClient.hpp"
int main()
{
    WSAData wsd;
    //启动Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) {
        cout << "WSAStartup Error = " << WSAGetLastError() << endl;
        return 0;
    }
    else {
        cout << "WSAStartup Success" << endl;
    }
    //创建套接字
    SOCKET csock = socket(AF_INET, SOCK_DGRAM, 0);//IPPROTO_UDP
    if (csock == SOCKET_ERROR) {
        cout << "socket Error = " << WSAGetLastError() << endl;
        return 1;
    }
    else {
        cout << "socket Success" << endl;
    }
    //Client 无需显式bind
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    string line;
#define NUM 1024
    char buffer[NUM];
    while (true)
    {
        //发送逻辑
        cout << "Please Enter# :";
        getline(cin, line);
        int ssize = sizeof server;
        int len = line.size();
        int n = sendto(csock, line.c_str(), len,0,(struct sockaddr*)&server,ssize);
        if (n < 0)
        {
            cerr << "sendto error!" << endl;
            break;
        }
        //收取逻辑
        buffer[0] = 0;
        sockaddr_in peer;
        int peer_len = sizeof(peer);
        n = recvfrom(csock, buffer, (int)(sizeof(buffer) - 1), 0, (struct sockaddr*)&peer, &peer_len);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "server返回的消息是#" << buffer << endl;
        }
        else break;
    }
    closesocket(csock);
    WSACleanup();
	return 0;
}